package com.kj.flytebrygge;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;


import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * This class does all the work for setting up and managing Bluetooth
 * connections with the robot microcontroller.
 * 
 * TODO: handle the case when the microcontroller is reset, but the 
 * bluetooth radiomodule isn't. The symptom of this is that any
 * pending replies from the microcontroller will not arrive. Perhaps
 * handle this by adding a timeout-functionality to the requeststuff, and
 * reconnecting from scratch if a request-reply times out? 
 * 
 * 
 */
public class BluetoothService {
    // Debugging
	private static final String TAG = "FlytebryggeBluetoothService";
    private static final boolean D = true;

    // standard uuid
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Member fields
    private Handler mHandler = null;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_CONNECTING = 1; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 2;  // now connected to a remote device


    /* message-related constants */
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    
    
    
    /**
     * Constructor. Prepares a new Bluetooth session.
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BluetoothService(Handler handler) {
        mState = STATE_NONE;
        mHandler = handler;
    }

    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the bluetooth service. Called by the Activity onResume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "BluetoothService.start() running");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_NONE);
        
	
	
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     */
    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(TAG, "connect to: " + device.getAddress());

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(TAG, "connected");

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}


        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(String message) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(message);
    }
    


    public int enqueueRequest(String message) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return -1;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        return r.enqueueRequest(message);
    }

    
    public int pendingRequestCount() {
	    // Create temporary object
	    ConnectedThread r;
	    // Synchronize a copy of the ConnectedThread
	    synchronized (this) {
	        if (mState != STATE_CONNECTED) return 0;
	        r = mConnectedThread;
	    }
	    return r.pendingRequestCount();
    }
    
    
    public void clearRequestReplyQueue() {
	    // Create temporary object
	    ConnectedThread r;
	    // Synchronize a copy of the ConnectedThread
	    synchronized (this) {
	        if (mState != STATE_CONNECTED) return;
	        r = mConnectedThread;
	    }
	    r.clearRequestReplyQueue();
    }
    
    
    public int totalRequestCount() {
	    // Create temporary object
	    ConnectedThread r;
	    // Synchronize a copy of the ConnectedThread
	    synchronized (this) {
	        if (mState != STATE_CONNECTED) return 0;
	        r = mConnectedThread;
	    }
	    return r.totalRequestCount();
    }
    

    
    public long getMilliSecondsSinceLastReqeustReply() {
	    // Create temporary object
	    ConnectedThread r;
	    // Synchronize a copy of the ConnectedThread
	    synchronized (this) {
	        if (mState != STATE_CONNECTED) return 0;
	        r = mConnectedThread;
	    }
	    return r.getMilliSecondsSinceLastReqeustReply();
    }
    

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_NONE);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
    	Log.i(TAG,"connectionLost");
        setState(STATE_NONE);

        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }


    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
            }
            mmSocket = tmp;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread");
            setName("ConnectThread");

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
            } catch (IOException e) {
                connectionFailed();
                Log.i(TAG, "Failed to connect to the bluetooth device '" + mmDevice.getAddress() + "': " + e.toString());
                // Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() socket during connection failure", e2);
                }
                // Start the service over to restart listening mode
                //BluetoothService.this.start();
                return;
            }

            // Reset the ConnectThread because we're done
            synchronized (BluetoothService.this) {
                mConnectThread = null;
            }

            // Start the connected thread
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
        	Log.i(TAG,"ConnectThread.cancel() starting");
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        	Log.i(TAG,"ConnectThread.cancel() finished");
        }
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private BluetoothSocket mmSocket;
        private InputStream mmInStream;
        //private final BufferedReader mmReader;
        private final OutputStream mmOutStream;
        private int mPendingRequestCount = 0;
        private int mTotalRequestCount = 0;
        private int mLastRequestNr;
		private long lastMessageNanoTime;

        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            this.lastMessageNanoTime=java.lang.System.nanoTime();

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            /*
            if( tmpIn != null ) {
            	mmReader = new BufferedReader(new InputStreamReader(tmpIn)); 
            } else {
            	mmReader = null; 
            }*/
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");

            // Keep listening to the InputStream while connected
            StringBuffer readMessage = new StringBuffer();
            
            while (true) {
                try {
                    // Read from the InputStream 
                	// NOTE: I originally tried to use a BufferedReader here (so that I could use
                	//       its readLine() method, but for some reason it didn't work to close
                	//       the socket then.
                	if( mmInStream == null ) {
                        Log.e(TAG, "disconnected (mmInStream == null)");
                        connectionLost();
                		break;
                	}
                	int inputByte = mmInStream.read();
                	if( inputByte == -1 ) {
                        Log.e(TAG, "disconnected (mmInStream.read() returned -1)");
                        connectionLost();
                		break;
                	}
                	                	
                	if( inputByte != 13 ) {
                		readMessage.append((char)inputByte);
                	} else {
                		Log.i(TAG, "Read " + readMessage.length() + " characters from the inputstream: '" + readMessage.toString() + "'");
                		readMessage.delete(0, readMessage.length());
	                    this.lastMessageNanoTime=java.lang.System.nanoTime();

	                    
	                    // TODO: implement proper request-functionality, with request callbacks etc. For
	                    //      now we just directly tries to update the mPendingRequestCount.
	                    if( mPendingRequestCount > 0 ) {
	                    	mPendingRequestCount--;
	                    }
	                    
	
	                    // Send the message to the UI Activity
	                    //mHandler.obtainMessage(MESSAGE_READ, readMessage)
	                    //        .sendToTarget();
                	}
                	
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

        
        
        
        /**
         * Write directly to the connected OutStream. Note: you should probably use the enqueueRequest()-method instead
         * @param buffer  The bytes to write
         */
        public void write(String message) {
        	byte[] buffer = message.getBytes();
        	Log.i(TAG, "Wrote message:" + message);

            try {
                mmOutStream.write(buffer);
                mmOutStream.flush();
                Log.i(TAG, "Wrote " + buffer.length + " bytes.");

                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
        }
        

        
        public int enqueueRequest(String message) {
        	// TODO: implement proper request handling, with request answer callbacks, etc.
        	//       For now we just send the message at once, with no flow control here.
        	mTotalRequestCount++;
        	mPendingRequestCount++;
        	this.write(mTotalRequestCount + " " + message);
        	return mTotalRequestCount;
        }

        
        public int pendingRequestCount() {
        	// TODO: implement proper request handling, with request answer callbacks, etc.
        	return mPendingRequestCount;
        }

        
        public long getMilliSecondsSinceLastReqeustReply() {
        	return (java.lang.System.nanoTime()-this.lastMessageNanoTime)/1000000;
        }
        

        public void clearRequestReplyQueue() {
        	// TODO: implement proper request handling, with request answer callbacks, etc.
        	// This is a hacky method that can be called if the usercode feels that
        	// some request-replies has been lost in transit.
        	mPendingRequestCount=0;
            this.lastMessageNanoTime=java.lang.System.nanoTime();
        }
        public int totalRequestCount() {
        	return mTotalRequestCount;
        }
    	

        public void cancel() {
        	Log.i(TAG,"ConnectedThread.cancel() starting");
        	
        	
            /* For some reason, the call to mmSocket.close() hangs
            try {
            	Log.i(TAG,"ConnectedThread.cancel() calling mmSocket.close()");
            	mmSocket.close();
            } catch (Exception e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
            */
        	
            mmSocket = null;
        	mmInStream = null;
        	
        	Log.i(TAG,"ConnectedThread.cancel() finished.");
            
        }
    }


}
